
// Copyright (c) WanSheng Intelligent Corp. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.


#define LOG_TAG "JSON"

#include "cJSON_ext.h"
#include "logs.h"
#include "stdlib.h"
#include "stdio.h"
#include "misc.h"
#include <string.h>
#include <unistd.h>


cJSON * cJSON_Parse_Data(const char *value, int len)
{
    if(value == NULL || len <= 0)
        return NULL;

    char * buf = (char *) value;
    bool alloc= false;
    if(value[len-1] != 0)
    {
        buf = (char*) malloc(len+1);
        memcpy(buf, value, len);
        buf[len] = 0;
        alloc = true;
    }

    cJSON * ret = cJSON_Parse(buf);
    if(alloc) free(buf);
    return ret;
}

cJSON * load_json_file_A(const char* path)
{
    cJSON * config_json = NULL;
    char *content = NULL;

    if(access(path, F_OK) != 0 )
    {
        //WARNING("load_json_file_A: %s not present", path);
        return nullptr;    
    }

    int len = load_file_to_memory(path, &content);
    if(len <= 0)
    {
        WALOG("Config %s can not be loaded", path);
        return nullptr;
    }

    config_json = cJSON_Parse((const char *)content);
    if(config_json == NULL)
    {
        WALOG("load_json_file_A: Invalid config file %s.",path);
        goto end;
    }
end:
    if(content) free(content);
    return config_json;
}


bool save_json_file(cJSON * json, const char* path)
{
    if(json == nullptr)
        return false;

    char * out = cJSON_Print(json);
    if(out == nullptr)
        return false;

    bool ret = save_content((char*)path, out, strlen(out));
    free(out);

    return ret;
}

const char *cJSONx_GetObjectString(cJSON * object, const char* item)
{
    cJSON * r = cJSON_GetObjectItem(object, item);
    if(cJSON_IsString(r))
        return r->valuestring;

    return NULL;
}

int cJSONx_GetObjectNumber(cJSON * object, const char* item, int default_val)
{
    cJSON * r = cJSON_GetObjectItem(object, item);
    if(cJSON_IsNumber(r))
        return r->valueint;

    return default_val;
}
